<template>
  <div class="app-container">
    <el-card>
      <div class="search-input-group">
        <el-form :model="searchForm" :inline="true">
          <el-form-item style="padding:5px" label="学号/工号">
            <el-input 
              v-model="searchForm.studentId" 
              placeholder="请输入学号/工号" 
              clearable
            />
          </el-form-item>
          <el-form-item style="padding:5px" label="用户编号">
            <el-input 
              v-model="searchForm.userId" 
              placeholder="请输入用户编号" 
              clearable
            />
          </el-form-item>
          <el-form-item style="padding:5px" label="高校代码">
            <el-input 
              v-model="searchForm.universityCode" 
              placeholder="请输入高校代码" 
              clearable
            />
          </el-form-item>
          <el-form-item style="padding:5px" label="用户名">
            <el-input 
              v-model="searchForm.username" 
              placeholder="请输入用户名" 
              clearable
            />
          </el-form-item>
          <el-form-item style="padding:5px" label="高校名称">
            <el-input 
              v-model="searchForm.universityName" 
              placeholder="请输入高校名称" 
              clearable
            />
          </el-form-item>
          <el-form-item style="padding:5px" label="审核状态">
            <el-select v-model="searchForm.dataStatus" placeholder="请选择审核状态" style="width: 150px;" clearable>
              <el-option label="已通过" :value="1" />
              <el-option label="已驳回" :value="2" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
            <el-button @click="handleResetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <div class="btn-group">
        <el-button 
          v-if="btnGroup.addb" 
          type="primary" 
          :icon="Plus"
          @click="showAddDialog"
        >
          添加
        </el-button>
        <el-button 
          v-if="btnGroup.editb" 
          type="success" 
          :icon="Edit"
          @click="showEditDialog"
          :disabled="multipleSelection.length !== 1"
        >
          修改
        </el-button>
        <el-button 
          v-if="btnGroup.deleteb" 
          type="danger" 
          :icon="Delete"
          @click="handleDelete"
          :disabled="multipleSelection.length <= 0"
        >
          删除
        </el-button>
      </div>
      
      <el-table 
        :data="dataList" 
        style="width: 100%" 
        row-key="id"
        @selection-change="handleSelectionChange"
        border
      >
        <el-table-column type="selection" width="40" />
        <el-table-column type="index" label="序号" width="80" show-overflow-tooltip/>
        <el-table-column prop="studentId" label="学号/工号" width="150" show-overflow-tooltip/>
        <el-table-column prop="userId" label="用户编号" width="150" show-overflow-tooltip/>
        <el-table-column prop="username" label="用户名" width="120" show-overflow-tooltip/>
        <el-table-column prop="universityCode" label="高校代码" width="120" show-overflow-tooltip/>
        <el-table-column prop="universityName" label="高校名称" min-width="150" show-overflow-tooltip/>
        <el-table-column prop="dataStatus" label="审核状态" width="100" show-overflow-tooltip>
          <template #default="scope">
            <el-tag 
              :type="getStatusTag(scope.row.dataStatus)"
              disable-transitions
            >
              {{ getStatusText(scope.row.dataStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" show-overflow-tooltip/>
        <el-table-column prop="updateTime" label="更新时间" show-overflow-tooltip/>
      </el-table>

      <!-- 分页组件 -->
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :total="pagination.total"
        :page-sizes="[10, 20, 50]"
        layout="total, sizes, prev, pager, next"
        background
        @current-change="handleCurrentChange"
        class="pagination"
      />
    </el-card>
    
    <!-- 添加学生对话框 -->
    <el-dialog
      title="添加学生信息"
      v-model="addDialogVisible"
      width="600px"
    >
      <el-form
        :model="operateDataForm"
        :rules="operateDataFormRules"
        ref="addFormRef"
        label-width="120px"
        label-position="left"
      >
        <el-form-item label="学号/工号" prop="studentId">
          <el-input 
            v-model="operateDataForm.studentId" 
            placeholder="请输入学号/工号"
          />
        </el-form-item>
        <el-form-item label="用户编号" prop="userId">
          <el-input 
            v-model="operateDataForm.userId" 
            placeholder="请输入用户编号"
          />
        </el-form-item>
        <el-form-item label="高校代码" prop="universityCode">
          <el-input 
            v-model="operateDataForm.universityCode" 
            placeholder="请输入高校代码"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAdd">确定</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 修改学生对话框 -->
    <el-dialog
      title="修改学生信息"
      v-model="editDialogVisible"
      width="600px"
    >
      <el-form
        :model="operateDataForm"
        :rules="operateDataFormRules"
        ref="editFormRef"
        label-width="120px"
        label-position="left"
      >
        <el-form-item label="数据编号" prop="id" disabled>
          <el-input 
            v-model="operateDataForm.id" 
            placeholder="数据编号"
          />
        </el-form-item>
        <el-form-item label="版本号" prop="dataVersion" disabled>
          <el-input 
            v-model="operateDataForm.dataVersion" 
            placeholder="版本号"
          />
        </el-form-item>
        <el-form-item label="学号/工号" prop="studentId">
          <el-input 
            v-model="operateDataForm.studentId" 
            placeholder="请输入学号/工号"
          />
        </el-form-item>
        <el-form-item label="用户编号" prop="userId">
          <el-input 
            v-model="operateDataForm.userId" 
            placeholder="请输入用户编号"
          />
        </el-form-item>
        <el-form-item label="高校代码" prop="universityCode">
          <el-input 
            v-model="operateDataForm.universityCode" 
            placeholder="请输入高校代码"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEdit">确定</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 删除确认对话框 -->
    <el-dialog
      title="确认删除"
      v-model="deleteDialogVisible"
      width="400px"
    >
      <p>确定要删除选中的 {{ multipleSelection.length }} 条学生信息吗？</p>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="submitDelete">确定删除</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { Plus, Edit, Delete, Search } from '@element-plus/icons-vue'
import { onMounted, reactive, ref } from "vue"
import { getStudentList, addStudent, updateStudent, deleteStudent } from "@/api/admin/student"

// 搜索表单数据
const searchForm = reactive({
  studentId: '',
  userId: '',
  universityCode: '',
  username: '',
  universityName: '',
  dataStatus: ''
})

// 固定参数源
const dataList = ref([])
const multipleSelection = ref([])
const isSearch = ref(false)
const btnGroup = reactive({
  addb: true,
  editb: true,
  deleteb: true
})
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 操作表单数据
const operateDataForm = reactive({
  id: '',
  dataVersion: '',
  studentId: '',
  userId: '',
  universityCode: ''
})

// 表单验证规则
const operateDataFormRules = {
  studentId: [
    { required: true, message: '请输入学号/工号', trigger: 'blur' }
  ],
  userId: [
    { required: true, message: '请输入用户编号', trigger: 'blur' }
  ],
  universityCode: [
    { required: true, message: '请输入高校代码', trigger: 'blur' }
  ]
}

// 对话框相关变量
const addDialogVisible = ref(false)
const editDialogVisible = ref(false)
const deleteDialogVisible = ref(false)
const addFormRef = ref(null)
const editFormRef = ref(null)

// 获取学生列表数据
const getDataList = () => {
  let res = getStudentList({...searchForm}, pagination.currentPage)
  res.then(res => {
    dataList.value = res.data?.records || []
    // 处理操作权限
    let opeStr = res.operateStr || '*'
    if(opeStr.includes("*") || opeStr.includes("c")) btnGroup.addb = true
    if(opeStr.includes("*") || opeStr.includes("u")) btnGroup.editb = true
    if(opeStr.includes("*") || opeStr.includes("d")) btnGroup.deleteb = true
    pagination.total = res.data?.total || 0
    pagination.pageSize = res.data?.size || 10
    pagination.currentPage = res.data?.current || 1
  })
}

// 搜索学生数据
const handleSearch = () => {
  isSearch.value = true
  let res = getStudentList({...searchForm}, pagination.currentPage)
  res.then(res => {
    dataList.value = res.data?.records || []
    pagination.total = res.data?.total || 0
    pagination.pageSize = res.data?.size || 10
    pagination.currentPage = res.data?.current || 1
  })
}

const handleResetSearch = () => {
  searchForm.studentId = ""
  searchForm.userId = ""
  searchForm.universityCode = ""
  searchForm.username = ""
  searchForm.universityName = ""
  searchForm.dataStatus = ""
  isSearch.value = false
  getDataList()
}

const handleSelectionChange = (selection) => {
  multipleSelection.value = selection
}

// 当前页改变时触发
const handleCurrentChange = (val) => {
  pagination.currentPage = val
  refreshList()
}

const refreshList = () => {
  if (isSearch.value) handleSearch()
  else getDataList()
}

// 重置操作表单
const resetOperateForm = () => {
  operateDataForm.id = ''
  operateDataForm.dataVersion = ''
  operateDataForm.studentId = ''
  operateDataForm.userId = ''
  operateDataForm.universityCode = ''
}

// 显示添加对话框
const showAddDialog = () => {
  resetOperateForm()
  addDialogVisible.value = true
}

// 显示编辑对话框
const showEditDialog = () => {
  if (multipleSelection.value.length === 1) {
    const selectedData = multipleSelection.value[0]
    operateDataForm.id = selectedData.id
    operateDataForm.dataVersion = selectedData.dataVersion || ''
    operateDataForm.studentId = selectedData.studentId
    operateDataForm.userId = selectedData.userId
    operateDataForm.universityCode = selectedData.universityCode
    editDialogVisible.value = true
  }
}

// 显示删除确认对话框
const handleDelete = () => {
  if (multipleSelection.value.length > 0) {
    deleteDialogVisible.value = true
  }
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    1: '已通过',
    2: '已驳回'
  }
  return statusMap[status] || '未知状态'
}

// 获取状态标签类型
const getStatusTag = (status) => {
  const tagMap = {
    1: 'success',
    2: 'danger'
  }
  return tagMap[status] || 'warning'
}

// 提交添加
const submitAdd = async() => {
  if (!addFormRef.value) return
  
  try {
    await addFormRef.value.validate()
    
    const addParams = {
      studentId: operateDataForm.studentId,
      userId: operateDataForm.userId,
      universityCode: operateDataForm.universityCode
    }
    
    console.log('添加参数:', addParams)
    await addStudent(addParams)
    addDialogVisible.value = false
    refreshList()
  } catch (error) {
    console.log('表单验证失败:', error)
  }
}

// 提交编辑
const submitEdit = async() => {
  if (!editFormRef.value) return
  
  try {
    await editFormRef.value.validate()
    
    const editParams = {
      id: operateDataForm.id,
      dataVersion: operateDataForm.dataVersion,
      studentId: operateDataForm.studentId,
      userId: operateDataForm.userId,
      universityCode: operateDataForm.universityCode
    }
    
    console.log('修改参数:', editParams)
    await updateStudent(editParams)
    editDialogVisible.value = false
    refreshList()
  } catch (error) {
    console.log('表单验证失败:', error)
  }
}

// 提交删除
const submitDelete = async() => {
  const deleteParams = {
    list: multipleSelection.value.map(item => item.id)
  }
  
  console.log('删除参数:', deleteParams)
  await deleteStudent(deleteParams)
  deleteDialogVisible.value = false
  refreshList()
}

onMounted(() => {
  getDataList()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

.btn-group {
  margin-bottom: 15px;
}

.btn-group .el-button {
  margin-right: 1px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.search-input-group {
  margin-bottom: 15px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.search-input-group .el-form-item {
  margin-bottom: 0;
  margin-right: 15px;
}
</style>